<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        .box{width: 200px;height: 100px;border: solid 2px black; position: absolute; left:0px; top:0;}
    </style>
</head>
<body>
    <div class="box"></div>
</body>
<script>
    var obox = document.querySelector(".box")

    document.onkeydown = function(eve){
        var e = eve || window.event;

        // 获取键码（兼容）
        // console.log(e.keyCode);
        // console.log(e.which);
        var code = e.keyCode || e.which;

        if(code == 32){
            obox.innerHTML = "按下了空格";
        }
        if(code == 13){
            obox.innerHTML = "按下了回车";
        }

        // 键盘控制元素的位置
        switch(code){
            case 37:
                obox.style.left = obox.offsetLeft - 10 + "px";
                break;
            case 38:
                obox.style.top = obox.offsetTop - 10 + "px";
                break;
            case 39:
                obox.style.left = obox.offsetLeft + 10 + "px";
                break;
            case 40:
                obox.style.top = obox.offsetTop + 10 + "px";
                break;
        }

    }
</script>
</html>